
import dao.EvenementDAO;
import dao.TypeBilletDAO;
import dao.TypebDAO;

import dao.BilletDAO;
import dao.GuichetDAO;
import dao.KitDAO;
import dao.MontantCaisseDAO;
 
import dao.VenteDAO;
import entity.Billet;
import entity.Evenement;
import entity.Guichet;
import entity.Kit;
import entity.MontantCaisse;
import entity.TypeBillet;
import entity.Typeb;
import entity.Vente;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import org.jboss.weld.context.ejb.Ejb;

@ManagedBean(name = "venteBean")
@SessionScoped
public class VenteBean {

    @Ejb
    BilletDAO billetDAO = new BilletDAO();
    @Ejb
    EvenementDAO evenementDAO = new EvenementDAO();
    @Ejb
    TypeBilletDAO typeBilletDAO = new TypeBilletDAO();
    @Ejb
    TypebDAO typebDAO = new TypebDAO();
    @Ejb
    MontantCaisseDAO montantCaisseDAO = new MontantCaisseDAO();
    @Ejb
    VenteDAO trans = new VenteDAO();
    List<TypeBillet> types;
    List<Evenement> evenements;
    List<Evenement> evkit = new ArrayList<Evenement>();
    Evenement selectedEvent;
    int id_event;
    List<Integer> ids_event;
    double prixTotal;
    int id_type_carte;
    double prix;
    Integer prixx;
    int places;
    int nbrSpec;
    Integer nbrPlaces = 1;
    int remise = 0;
    private String sn;

    public VenteBean() {
        selectedEvent = new Evenement();
    }

    public List<Evenement> getEvkit() {
        return evkit;
    }

    public void setEvkit(List<Evenement> evkit) {
        this.evkit = evkit;
    }

    public List<TypeBillet> getTypes() {
        return typeBilletDAO.findAll();
    }

    public Evenement getSelectedEvent() {

        return selectedEvent;
    }

    public Integer getNbrPlaces() {
        return nbrPlaces;
    }

    public void setNbrPlaces(Integer nbrPlaces) {
        this.nbrPlaces = nbrPlaces;
    }

    public void setSelectedEvent(Evenement selectedEvent) {
        this.selectedEvent = selectedEvent;
    }

    public Integer getPrixx() {
        return prixx;
    }

    public void setPrixx(Integer prixx) {
        this.prixx = prixx;
    }

    public void setTypes(List<TypeBillet> types) {
        this.types = types;
    }

    public double getPrix() {
        return prix;
    }

    public void setPrix(double prix) {
        this.prix = prix;
    }

    public int getId_event() {
        return id_event;
    }

    public void setId_event(int id_event) {
        this.id_event = id_event;
    }
    private Integer idTypeB;

    public String getSn() {
        return sn;
    }

    public void setSn(String sn) {
        this.sn = sn;
    }

    public Integer getIdTypeB() {
        return idTypeB;
    }

    public void setIdTypeB(Integer idTypeB) {
        this.idTypeB = idTypeB;
    }
    private Integer prixkit;
    double prixRemise;

    public double getPrixRemise() {
        prixRemise = prixkit - ((prixkit + 0.0) * remise / 100);
        return prixRemise;
    }

    public void setPrixRemise(double prixRemise) {
        this.prixRemise = prixRemise;
    }

    public Integer getPrixkit() {
        prixkit = 0;
        for (int i = 0; i < typebsKit.size(); i++) {
            prixkit += typebsKit.get(i).getPrix();
            // System.out.println("typebsKit.get(i).getPrix()=" + typebsKit.get(i).getPrix());
        }
        return prixkit;
    }
    private Integer remi;

    public Integer getRemi() {


        return remi;
    }

    public void setRemi(Integer remi) {
        this.remi = remi;
    }

    public void setPrixkit(Integer prixkit) {
        this.prixkit = prixkit;
    }

    public int getRemise() {
        if (typebsKit.size() <= 9 && typebsKit.size() >= 5) {
            remise = 5;
        } else if (typebsKit.size() <= 19 && typebsKit.size() >= 10) {
            remise = 10;
        } else if (typebsKit.size() <= 31 && typebsKit.size() >= 20) {
            remise = 20;
        } else if (typebsKit.size() < 5) {
            remise = 0;
        }
        return remise;
    }

    public void setRemise(int remise) {
        this.remise = remise;
    }

    public List<Integer> getIds_event() {
        return ids_event;
    }

    public void setIds_event(List<Integer> ids_event) {
        this.ids_event = ids_event;
    }

    public double getPrixTotal() {
        return prixTotal;
    }

    public void setPrixTotal(double prixTotal) {
        this.prixTotal = prixTotal;
    }

    public int getNbrSpec() {
        return nbrSpec;
    }

    public void setNbrSpec(int nbrSpec) {
        this.nbrSpec = nbrSpec;
    }

    public int getId_type_carte() {
        return id_type_carte;
    }

    public void setId_type_carte(int id_type_carte) {
        this.id_type_carte = id_type_carte;
    }

    public Typeb getTypeB() {
        return typeB;
    }

    public void setTypeB(Typeb typeB) {
        this.typeB = typeB;
    }

    public List<Evenement> getEvenements() {
        return evenementDAO.findAll();
    }

    public void setEvenements(List<Evenement> evenements) {
        this.evenements = evenements;
    }

    public void prixIt() {
        TypeBillet t = typeBilletDAO.findById(id_type_carte);
        places = t.getQuantite();
        prix = t.getPrix();
    }

    public void prixIt1() {

        TypeBillet t = typeBilletDAO.findById(id_type_carte);
        places = t.getQuantite();
        //   System.out.println("prix=" + t.getPrix());
        prixTotal = t.getPrix() * ids_event.size();
    }

    public void remiseIt() {

        if (ids_event.size() <= 9 && ids_event.size() >= 5) {
            remise = 5;
        } else if (ids_event.size() <= 20 && ids_event.size() >= 10) {
            remise = 10;
        } else if (ids_event.size() <= 31 && ids_event.size() >= 21) {
            remise = 20;
        } else if (ids_event.size() < 5) {
            remise = 0;
        }
    }

    public int getPlaces() {
        return places;
    }

    public void setPlaces(int places) {
        this.places = places;
    }
    ticket[] tickts;
    private double prixAchat;

    public double getPrixAchat() {
        return prixAchat;
    }

    public void setPrixAchat(double prixAchat) {
        this.prixAchat = prixAchat;
    }
    boolean hand;

    public boolean isHand() {
        return hand;
    }

    public void setHand(boolean hand) {
        this.hand = hand;
    }

    public String vendre() {
        if (handicap) {
            remi = 50;
        } else {
            remi = 0;
        }
        //System.out.println("handicap :" + nbrPlaces);
        if (nbrPlaces <= 20) {
            //   System.out.println("nbplaces=" + nbrPlaces);
            //  System.out.println("SelectedEvent:" + selectedEvent.getTitre());
            if (Integer.parseInt(findStock1(selectedEvent)) - nbrPlaces >= 0) {
                //  System.out.println(" dif=" + (Integer.parseInt(findStock1(selectedEvent)) - nbr));
                tickts = new ticket[nbrPlaces];
                typeB = (Typeb) typebDAO.findByTypeAndFes(selectedEvent.getId(), 2).get(0);
                prix = nbrPlaces * typeB.getPrix();
                prixAchat = prix - (prix * 1.0 * remi / 100);



                return "vente_2.xhtml?faces-redirect=true";
            } else {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "stock restant :" + findStock1(selectedEvent), ""));

                return "";
            }
        } else {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Nombre Max 5", ""));

            return "";
        }

    }

    public String vendre2() {
        if(selectedEvent.getId()==6)
        {nbr=1;return"vente_1.xhtml?faces-redirect=true";}
        handicap = hand;
        if (handicap) {
            remi = 50;
        } else {
            remi = 0;
        }
        //    System.out.println("handicap :" + handicap);
        if (nbr <= 5) {
            if (Integer.parseInt(findStock(selectedEvent)) - nbr >= 0) {
                nbrPlaces = nbr;
                tickts = new ticket[nbrPlaces];
                typeB = (Typeb) typebDAO.findByTypeAndFes(selectedEvent.getId(), 1).get(0);
                prix = nbrPlaces * typeB.getPrix();
                prixAchat = prix - (prix * 1.0 * remi / 100);
                //    System.out.println("The prixAchat=" + prixAchat);
                return "vente_2.xhtml?faces-redirect=true";
            } else {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "stock restant :" + findStock(selectedEvent), ""));

                return "";
            }
        } else {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Nombre Max 5", ""));
            return "";
        }

    }

    public String redirect() {
        typebsKit = new ArrayList<Typeb>();
        integers = new ArrayList<Integer>();
        sn = "";
        remiseDeKit = 0;
        prixDeKit = 0;
        remise = 0;
        return "vente_1.xhtml?faces-redirect=true";
    }

    public void enregistrer() {
        if (carNew.size() == nbrPlaces) {
            trans.beginTransaction();
            Vente v = new Vente();
            v.setTime(new Date());
            v.setDate(new Date());
            v.setNombre(carNew.size());
            FacesContext context = FacesContext.getCurrentInstance();
            guichetBean bean = (guichetBean) context.getApplication().evaluateExpressionGet(context, "#{guichetBean}", guichetBean.class);
            Guichet guichet = new GuichetDAO().findById(bean.getUser().getId());
            v.setGuichet(guichet);
            Billet b = (Billet) billetDAO.findByProperty("numero", carNew.get(0)).get(0);
            Typeb typeb = new Typeb();
            typeb = b.getTypeb();
            // System.out.println("the remise =" + remi);
            v.setRemise(remi);
            v.setEvenement(selectedEvent);
            //   System.out.println("the prix total is =" + prixTotal);
            v.setPrixTotal(prix);
            v.setPrixUnitaire(typeb.getPrix());
            v.setPrixUnitaire(typeb.getPrix());
            v.setPrixAchat(prixAchat);
            v.setRemise(remi);
            MontantCaisse montantCaisse = (MontantCaisse) montantCaisseDAO.findByProperty("guichet", guichet).get(0);
            double m = montantCaisse.getMontant();
            montantCaisse.setMontant(prixAchat + m);
            montantCaisseDAO.merge(montantCaisse);
            trans.save(v);
            for (int i = 0; i < carNew.size(); i++) {
                b = (Billet) billetDAO.findByProperty("numero", carNew.get(i)).get(0);
                b.setVente(v);
                //   System.out.println("sn=" + b.getNumero());
                b.setVendu(true);
                billetDAO.save(b);
                b = new Billet();
            }

            System.out.println(" stock new ="+(typeb.getStock() - carNew.size()));
            typeb.setStock(typeb.getStock() - carNew.size());
            typebDAO.merge(typeb);
            trans.commit();
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, " Vente enregistré", ""));
            carNew = new ArrayList<String>();
            handicap = false;
            //nbr = nbrPlaces = 1;
        } else {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Nombres des codes inferieure a celui saisie", ""));
        }
    }
    int nbr = 1;

    public int getNbr() {
        return nbr;
    }

    public void setNbr(int nbr) {
        this.nbr = nbr;
    }

    public ticket[] getTickts() {
        return tickts;
    }

    public void setTickts(ticket[] tickts) {
        this.tickts = tickts;
    }
    private Typeb typeB;

    public String vend() {

        typeB = (Typeb) typebDAO.findByTypeAndFes(selectedEvent.getId(), 2).get(0);
        //   System.out.println("das" + typeB.getPrix());
        return "vente_2.xhtml?faces-redirect=true";

    }
    boolean handicap = false;

    public boolean isHandicap() {
        return handicap;
    }

    public void setHandicap(boolean handicap) {
        this.handicap = handicap;
    }
    private List<String> carNew = new ArrayList<String>();

    public List<String> getCarNew() {
        return carNew;
    }

    public void setCarNew(List<String> carNew) {
        this.carNew = carNew;
    }
    private String ser;

    public String getSer() {
        return ser;
    }

    public void setSer(String ser) {
        this.ser = ser;
    }

    public void delete(String s) {
        //int i = carNew.indexOf(s);
        carNew.remove(s);
        // carNewCIN.remove(i);
    }

    public void vider() {
        ser = null;

        carNew = new ArrayList<String>();

    }

    public String createNew() {
        //   System.out.println("nbrplaces=" + nbrPlaces);
        
        if (carNew.size() < nbrPlaces) {
            if (ser.contains(" ") || ser.length() == 0) {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_FATAL, " numero Invalide", ""));

            } else if (!carNew.contains(ser)) {
                if(ser.contains("="))
                    ser=ser.replaceAll("=", "-");
                List<Billet> billets = billetDAO.findByProperty("numero", ser);
                if (billets.size() > 0) {
                    if (billets.get(0).getTypeb().getId() >= 1 && billets.get(0).getTypeb().getId() <= 62) {
                        if (billets.size() > 0) {
                            //      System.out.println("id Type b" + billets.get(0).getTypeb().getId());
                            if (billets.get(0).getTypeb().getEvenement().getId() == selectedEvent.getId()
                                    && billets.get(0).getTypeb().getTypeBillet().getModele().equals(typeB.getTypeBillet().getModele())) {
                                if (billets.get(0).getVendu() != true) {
                                    carNew.add(ser);
                                    FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, " Billet généré", ""));
                                    if (carNew.size() == nbrPlaces) {
                                        enregistrer();
                                    }
                                } else {
                                    FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, " Billet vendu deja", ""));
                                }

                            } else {
                                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Ce billet appatient à un autre spectacle ou modele ", ""));
                            }
                        } else {
                            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Ce type de billet n'est pas à vendre ", ""));
                        }

                        //*******************

                    } else {
                        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, " ce billet n'existe pas ", ""));

                    }
                } else {
                    FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_FATAL, " numero Invalide", ""));
                }



            } else {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, " Billet dèja généré", ""));
            }

        } else {
        }

        ser = "";
        return null;
    }

    public String createToo() {
        List<Billet> billets = billetDAO.findByProperty("numero", ser);
        //  System.out.println("numero:" + ser);
        //   System.out.println("bill    " + billets.size());
        return null;
    }
    private Evenement selectedEvKit;

    public Evenement getSelectedEvKit() {
        return selectedEvKit;
    }

    public void setSelectedEvKit(Evenement selectedEvKit) {
        this.selectedEvKit = selectedEvKit;
    }
    List<Typeb> typebsKit = new ArrayList<Typeb>();

    public List<Typeb> getTypebsKit() {
        return typebsKit;
    }

    public void setTypebsKit(List<Typeb> typebsKit) {
        this.typebsKit = typebsKit;
    }
    List<Integer> integers = new ArrayList<Integer>();

    public void ajoutChaise(Evenement e) {


        //   System.out.println("remise=" + remise + " size=" + typebsKit.size());
        typeB = (Typeb) typebDAO.findByEventChaise(e.getId()).get(0);
        //    System.out.println("size integers:" + integers.size());
        if (typeB.getStock() > 0) {
            //        System.out.println("asdasdasd " + (!integers.contains(typeB.getEvenement().getId())));
            if (!integers.contains(typeB.getEvenement().getId())) {
                integers.add(typeB.getEvenement().getId());
                typebsKit.add(typeB);
                prixDeKit += typeB.getPrix();
                remiseDeKit = prixDeKit - (prixDeKit * 1.0 * getRemise() / 100);
                //  System.out.println("stock=" + typeB.getStock());
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Spectacle ajouté", ""));
            } else {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Spectacle existe", ""));
            }

        } else {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Spectacle complé", ""));
        }


    }
    double remiseDeKit;

    public double getRemiseDeKit() {

        return remiseDeKit;
    }

    public void setRemiseDeKit(double remiseDeKit) {
        this.remiseDeKit = remiseDeKit;
    }

    public void ajoutGradin(Evenement e) {

        if (typebsKit.size() <= 9 && typebsKit.size() >= 5) {
            remise = 5;
        } else if (typebsKit.size() <= 20 && typebsKit.size() >= 10) {
            remise = 10;
        } else if (typebsKit.size() <= 31 && typebsKit.size() >= 21) {
            remise = 20;
        } else if (typebsKit.size() < 5) {
            remise = 0;
        }
        //  System.out.println("remise=" + remise);
        typeB = (Typeb) typebDAO.findByEventGradin(e.getId()).get(0);
        //  System.out.println("size integers:" + integers.size());
        if (typeB.getStock() > 0) {
            if (!integers.contains(typeB.getEvenement().getId())) {
                integers.add(typeB.getEvenement().getId());
                //    System.out.println("stock=" + typeB.getStock());
                typebsKit.add(typeB);
                prixDeKit += typeB.getPrix();
                remiseDeKit = prixDeKit - (prixDeKit * 1.0 * getRemise() / 100);
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Spectacle ajouté", ""));
            } else {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Spectacle existe", ""));
            }

        } else {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Spectacle complé", ""));
        }
    }
    KitDAO kitDAO = new KitDAO();
    double prixDeKit;

    public void enregistrerKit() {
        System.out.println("sn kit="+sn);
        sn=sn.replaceAll("=", "-");
        if (typebsKit.size() == 0) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Le kit est vide", ""));
        } else if (!sn.isEmpty()) {
            kitDAO.beginTransaction();
            List<Billet> lists = billetDAO.findByProperty("numero", sn);
            if (lists.size() > 0) {

                Billet b = (Billet) lists.get(0);
                if (b.getTypeb().getTypeBillet().getId() == 14) {
                    Typeb typebKito = b.getTypeb();
                    int k = typebKito.getStock();
                    if (k > 0) {
                        Kit kit = new Kit();
                        kit.setBillet(b);
                        String s = "";
                        FacesContext context = FacesContext.getCurrentInstance();
                        guichetBean bean = (guichetBean) context.getApplication().evaluateExpressionGet(context, "#{guichetBean}", guichetBean.class);
                        for (int i = 0; i < typebsKit.size(); i++) {
                            s += typebsKit.get(i).getEvenement().getId() + ";";
                            int kk = typebsKit.get(i).getStock();
                            //  System.out.println("kk=" + kk);
                            typebsKit.get(i).setStock(kk - 1);
                            typebDAO.merge(typebsKit.get(i));
                        }

                        kit.setNombre(typebsKit.size());
                        kit.setGuichet(bean.getUser());
                        kit.setIdsSpec(s);
                        kit.setDate(new Date());
                        kit.setTime(new Date());
                        kit.setRemise(remise);
                        kit.setPrixTotal(prixDeKit);
                        kit.setPrixAchat(remiseDeKit);
                        typebKito.setStock(k-1);
                        typebDAO.merge(typebKito);
                        MontantCaisse montantCaisse = (MontantCaisse) montantCaisseDAO.findByProperty("guichet", bean.getUser()).get(0);
                        double m = montantCaisse.getMontant();
                        montantCaisse.setMontant(remiseDeKit + m);
                       
                        montantCaisseDAO.merge(montantCaisse);
                        kitDAO.save(kit);
                        kitDAO.commit();
                        remise = 0;
                        prixDeKit = 0;
                        remiseDeKit = 0;
                        typebsKit = new ArrayList<Typeb>();
                        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Kit Enregistré", ""));

                    } else {
                        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Stock Kit est fini", ""));
                    }


                } else {
                    FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Ce billet n'est pas un kit", ""));
                }

            } else {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Ce billet n'existe pas", ""));
            }

        } else {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "SN est vide", ""));
        }

    }

    public double getPrixDeKit() {
        return prixDeKit;
    }

    public void setPrixDeKit(double prixDeKit) {
        this.prixDeKit = prixDeKit;
    }

    public void ajoutKit(Evenement e) {
        if (!evkit.contains(e)) {
            evkit.add(e);

            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Spectacle ajouté", ""));
        }

    }

    public void remove(Typeb e) {
        integers.remove(e.getEvenement().getId());
        typebsKit.remove(e);
        prixDeKit -= e.getPrix();
        // System.out.println("remise=" + remise);
        remiseDeKit = prixDeKit - (prixDeKit * 1.0 * remise / 100);
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Spectacle retiré", ""));
    }
    TypebDAO typebDAO1 = new TypebDAO();

    public String findStock(Evenement e) {
        Typeb typeb = (Typeb) typebDAO1.findByEventChaise(e.getId()).get(0);
        return typeb.getStock() + "";
    }

    public String findStock1(Evenement e) {
        //  System.out.println("e="+e.getId());
        Typeb typeb = (Typeb) typebDAO1.findByEventGradin(e.getId()).get(0);
        return typeb.getStock() + "";
    }

    public String retour() {
        carNew = new ArrayList<String>();
        nbrPlaces = 1;
        nbr = 1;
        typeB = new Typeb();
        prix = 0;
        remi = 0;
        prixAchat = 0;
        return "vente_1.xhtml?faces-redirect=true";
    }
}
